package com.example.wifistatedemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Parcelable;
import android.util.Log;

public class WifiChangeReceiver extends BroadcastReceiver {
	
	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {

		if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
			Log.i("receiver", "WIFI收到消息！ACTION = " + intent.getAction());
			// 这个监听wifi的打开与关闭，与wifi的连接无关
			int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
			Log.i("receiver", "wifiState = " + wifiState);
			// switch (wifiState) {
			// case WifiManager.WIFI_STATE_DISABLED:
			// break;
			// case WifiManager.WIFI_STATE_DISABLING:
			// break;
			// //
			// }
		}

		if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
			Log.i("receiver", "NETWORK收到消息！ACTION = " + intent.getAction());
			Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
			if (null != parcelableExtra) {
				NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
				State state11 = networkInfo.getState();
				boolean isConnected = state11 == State.CONNECTED;// 当然，这边可以更精确的确定状态
				
				State state = networkInfo.getState();
				if (state == State.CONNECTED) {
					Log.i("receiver", "State ----->CONNECTED");
				}else if (state == State.CONNECTING) {
					Log.i("receiver", "State ----->CONNECTING");
				}else if (state == State.DISCONNECTED) {
					Log.i("receiver", "State ----->DISCONNECTED");
				}else if (state == State.DISCONNECTING) {
					Log.i("receiver", "State ----->DISCONNECTING");
				}else {
					Log.i("receiver", "UNKNOWN STATE");
				}
				
			}
		}

		// 如果wifi状态改变，则会触发
		// if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
		// // wifi改变时，接收器会获得装有改变信息的intent
		// Parcelable mInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
		//
		// if (mInfo != null) {
		// NetworkInfo mNetworkInfo = (NetworkInfo) mInfo;
		// DetailedState state = mNetworkInfo.getDetailedState();
		// Log.i("receiver", "state = " + state.toString());
		// }else {
		// Log.i("receiver", "mInfo == null");
		// }
		// }else {
		// Log.i("receiver", "ACTION not match");
		// }
	}

}
